//
//  HMComposeViewController.swift
//  Black22
//
//  Created by Apple on 16/11/24.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposeViewController: UIViewController {

    private lazy var titleLabel: UILabel = {
        let label = UILabel(fontSize: 17, textColor: UIColor.darkGray)
        if let name = HMUserAccountViewModel.sharedUserAccount.userAccount?.name {
            let title = "发微博\n" + name
            
            let range = (title as NSString).range(of: name)
            
            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: title)
            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], range: range)
            label.attributedText = attributedStr
            
            
            
        } else {
            label.text = "发微博"
        }
        
        label.textAlignment = .center
        label.numberOfLines = 0
        label.sizeToFit()
        return label
    }()
    
    private lazy var sendButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        button.size = CGSize(width: 45, height: 35)
        return button
    }()
    
    //  添加textview
    fileprivate lazy var textView: HMComposeTextView = {
        let view = HMComposeTextView()
        //  是否隐藏纠错提示
        //  textView.autocorrectionType = .no
        view.delegate = self
        //  垂直方向弹簧开启
        view.alwaysBounceVertical = true
        view.placeHolder = "哈哈炼金狂士对方即可会计师对方可垃圾时打开了飞机快乐；就 阿萨德飞机开始的考虑；发斯蒂芬"
        view.font = UIFont.systemFont(ofSize: 13)
        return view
    }()
    //  toolbar
    fileprivate lazy var toolBar: HMComposeToolBar = {
        let toolBar = HMComposeToolBar()
        return toolBar
    }()
    
    //  配图
    fileprivate lazy var pictureViwe: HMComposePictrueView = {
        let picView = HMComposePictrueView()
        picView.backgroundColor = self.textView.backgroundColor
        return picView
    }()
    
    //  表情键盘视图
    fileprivate lazy var emotionKeyBoard: HMEmoticonKeyBoardView = {
        let keyboard = HMEmoticonKeyBoardView()
        keyboard.size = CGSize(width: self.textView.width, height: 216)
        return keyboard
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupUI()
    }

    
    private func setUpNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    private func setupUI() {
        
        //  监听键盘frame的改变的通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardChangeFrame(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //  监听表情按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedEmoticonButtonOperation(noti:)), name: NSNotification.Name(rawValue: ClickEmoticonButtonNoticationName), object: nil)
        //  监听删除表情按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedDeleteEmoticonButtonOperation(noti:)), name: NSNotification.Name(ClickDeleteEmoticonNoticationName), object: nil)
        
        setUpNavUI()
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureViwe)
        textView.snp_makeConstraints { (make) in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        toolBar.snp_makeConstraints { (make) in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(35)
        }
        
        pictureViwe.snp_makeConstraints { (make) in
            make.centerX.equalTo(textView)
            make.top.equalTo(textView).offset(100)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
        //  主要循环引用
        toolBar.callBack = { [weak self] (type: HMComposeToolBarType) -> () in
            switch type {
            case .picture:
                print("图片")
                self?.didSelectedPicture()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self?.didSelectEmoticon()
            case .add:
                print("加号")
                
                
            }
            
        }
        
        pictureViwe.addImageCallBack = { [weak self] in
            
            self?.didSelectedPicture()
            
        }
        
        
        
    }
    
    // MARK:    --删除表情按钮的点击
    @objc private func didSelectedDeleteEmoticonButtonOperation(noti: Notification) {
        //  删除textView内容操作
        textView.deleteBackward()
    }
    
    // MARK:    --表情按钮的点击
    @objc private func didSelectedEmoticonButtonOperation(noti: Notification) {
    
        let emoticon = noti.object as! HMEmoticon
        
        textView.insertEmoticon(emoticon: emoticon)
        
        //  保存最近表情
        HMEmoticonTools.sharedTools.saveRecentEmoticonArray(emoticon: emoticon)
        //  刷新首页数据
        emotionKeyBoard.reloadRecentData()
        
        
//        if emoticon.type == "0" {
//            //  图片，插入富文本
////            textView.text = emoticon.chs!
//            //  记录上次的富文本
//            let lastAttributedStr = NSMutableAttributedString(attributedString: textView.attributedText)
//            //  根据路径创建图片对象
//            let image = UIImage(named: emoticon.fullPath!)
//            //  根据图片对象创建文本附件
//            let attachMent = NSTextAttachment()
//            attachMent.image = image
//            let lineHeight = textView.font!.lineHeight
//            //  设置图片大小
//            attachMent.bounds = CGRect(origin: CGPoint(x: 0, y: -4), size: CGSize(width: lineHeight, height: lineHeight))
//            //  根据文本附件创建富文本
//            let attributedStr = NSAttributedString(attachment: attachMent)
////            lastAttributedStr.append(attributedStr)
//            
//            //  获取选中的范围
//            var selectRange = textView.selectedRange
//            //  替换指定的范围的富文本
//            lastAttributedStr.replaceCharacters(in: selectRange, with: attributedStr)
//            
//            //  开始位置
//            selectRange.location += 1
//            //  长度
//            selectRange.length = 0
//            
//            //  设置富文本字体大小
//            lastAttributedStr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, lastAttributedStr.length))
//            
//            //  设置富文本
//            textView.attributedText = lastAttributedStr
//            //  设置选中范围
//            textView.selectedRange = selectRange
//            
//            
//        } else {
//            //  插入文字
//            
//            textView.text = (emoticon.code! as NSString).emoji()
//            
//        }
        
        
    }
    
    
    // MARK:    --点击发送按钮
    @objc private func sendAction() {

        //  代码抽取到HMComposeTextView+Extension分类中
//        var result = ""
//        //  遍历富文本的属性获取对应的表情描述供新浪微博使用
//        textView.attributedText.enumerateAttributes(in: NSMakeRange(0, textView.attributedText.length), options: [], using: { (info, range, _) -> Void in
//            if let attachment = info["NSAttachment"] as? HMTextAttachment {
//                //  如果是文本附件表示是图片
//                //  通过文本附件获取对应的表情模型
//                if let emoticon = attachment.emoticon {
//                    result += emoticon.chs!
//                }
//                
//            } else {
//                //  文字富文本
//                let selectedAttributed = textView.attributedText.attributedSubstring(from: range)
//                result += selectedAttributed.string
//            }
//        })
//        
        
        
        let accessToken = HMUserAccountViewModel.sharedUserAccount.accessToken!
        let text = textView.emoticonText
//        let text = textView.text!
        
        SVProgressHUD.show()
        
        if pictureViwe.images.count > 0 {
            
            let image = pictureViwe.images.first!
            HMNetworkTools.sharedTools.upload(accessToken: accessToken, status: text, image: image, callBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                    print(error!)
            
                    return
                    
                }
                
                SVProgressHUD.showSuccess(withStatus: "发送成功")
            })
            
        
        } else {
            //  发送只有文字的微博
            HMNetworkTools.sharedTools.update(accessToken: accessToken, status: text, callBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                    print(error!)
                    return
                }
                
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                
            })
        }
        
    }
    
    //  键盘frame的改变
    @objc private func keyBoardChangeFrame(noti: Notification) {
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //  更新约束
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScreenHeight)
        }
        //  约束动画
        UIView.animate(withDuration: duration, animations: {
            self.view.layoutIfNeeded()
        })
        
    }
    
    
    
    
    // MARK:    --取消
    @objc private func cancelAction() {
        self.view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
   
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
  

}

//  处理点击toolbar按钮逻辑
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    //  点击表情
    func didSelectEmoticon() {
        //  设置inputView
        if textView.inputView == nil {
            //  进入表情键盘
            textView.inputView = emotionKeyBoard
            toolBar.showIcon(isEmoticon: true)
            
        } else {
            //  进入系统键盘
            textView.inputView = nil
            toolBar.showIcon(isEmoticon: false)
        }
        
        //  设置第一响应者
        textView.becomeFirstResponder()
        //  重新加载自定义的inputview视图
        textView.reloadInputViews()
        
        
        
        
    }
    
    
    //  点击图片
    func didSelectedPicture() {
        let imagePickerCtr = UIImagePickerController()
        //  来源类型
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePickerCtr.sourceType = .camera
        } else {
            imagePickerCtr.sourceType = .photoLibrary
        }
        //  编辑图片
//        imagePickerCtr.allowsEditing = true
        imagePickerCtr.delegate = self
        //
        self.present(imagePickerCtr, animated: true, completion: nil)
    }
    // MARK:    --UIImagePickerControllerDelegate
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //  原始图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        let currentImage = scaleImage(scaleWidth: 200, image: image)
        //  添加图片
        pictureViwe.addImage(image: currentImage)
        //  图片选择浏览器销毁
        picker.dismiss(animated: true, completion: nil)
    }
    
    
    //  根据压缩后的宽度，等比压缩图片
    func scaleImage(scaleWidth: CGFloat, image: UIImage) -> UIImage {
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        UIGraphicsBeginImageContext(scaleSize)
        
        image.draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return resultImage!
    }
    
    
}

extension HMComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        //  有内容文字右边按钮可用
        self.navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    //  开始拖动
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    

}


